(function(app){
	app
		.controller("content_01_inputCtrl",["$scope","myFactory",'$http','$stateParams','$state',"$q",'$timeout','$location','$ionicHistory',function($scope,myFactory,$http,$stateParams,$state,$q,$timeout,$location,$ionicHistory){

			//接收参数
			var itemId = $stateParams.changeTypeId;//变更项目ID
			var chdrnum01 =  $stateParams.chdrnum01; //保单号
			var chdrcoy = $stateParams.chdrcoy; //保单公司号码
			var searchParam = $stateParams.searchParam;
			var policyData;//保单信息
			var initFlag = false;//检测初始化是否完成标志
			/*S2019070309187 - 电子保全增加个人信息授权内容需求 add by yangyan 20190717 start*/
			$scope.readFlag = false;//阅读协议标志，默认为false
			/*S2019070309187 - 电子保全增加个人信息授权内容需求 add by yangyan 20190717 end*/

/********************************************初始化函数begin************************************************/
			//androidH();
			var item="";
			var isOneYearCrtFlag=true;
			var taxBenefitRole="";//受益人角色
			var taxClientNo="";//投保人/受益人客户号
			var policy;//基础信息
			//初始化查询变更项内容
			$scope.load = function () {
				myFactory.loadingShow();//显示加载圈
				var token=sessionStorage.getItem("token");
				var timestamp=myFactory.getTimetamp();
				/*护网行动 update by huanghaokun 20220705 start*/
				var sfis= "itemId-token-timestamp";
				var signStr="itemId="+itemId+"&token="+token+"&timestamp="+timestamp;//encodeURI(name)
				/*护网行动 update by huanghaokun 20220705 end*/
				var sign = myFactory.hex(signStr);
				$http({
					method: 'GET',
					url: app.domain + 'input/initContentItem.action',
					/*护网行动 update by huanghaokun 20220705 start*/
					params: {'itemId': itemId,'sign':sign,'sfis':sfis,'token':token,'timestamp':timestamp}
					/*护网行动 update by huanghaokun 20220705 end*/
				}).then(function successCallback(response) {
					if (response.data.success) {
						$scope.chdrnum01=response.data.data.policy.base.chdrnum01;
						$scope.item01=response.data.data.modelMap.item01;
						isOneYearCrtFlag=response.data.data.modelMap.isOneYearCrtFlag;
						taxBenefitRole=response.data.data.modelMap.taxBenefitRole;
						taxClientNo=response.data.data.modelMap.taxClientNo;
						policy = response.data.data.policy;
						item=$scope.item01;
						initFlag = true;
						
						var address=item.address_1;
						var province = null;
						var prov = "";
						var type = 0;//0-普通，1-直辖市，2-特别行政区
						for (var i = 0; i < unshow_provinces_b.length; i++) {
							if (address!="" && address!=undefined && address.indexOf(unshow_provinces_b[i]) == 0) {
								prov = unshow_provinces_b[i];
								type = 2;
								break;
							}
						}
						if (prov != "" && type==2) {//2-特别行政区
							console.log('初始化特别行政区获取省名='+prov+",行政区类型type="+type);
							$("#provinceNameOld").val(prov);
						}
						
					}
					myFactory.loadingHide();
				}, function errorCallback(response) {
					myFactory.loadingHide();
					myFactory.alert("","初始化查询变更项内容失败!","info");
				});
			}
			
/********************************************初始化函数begin************************************************/
			$scope.data = {
				radioFlag: true
			},
			//单选按钮样式控制
			$scope.isLabel = function(){
				$scope.data.radioFlag = true;
			}
			$scope.notLabel = function(){
				$scope.data.radioFlag = false;
			}			
			//重新受理
			$scope.renew = function(){
				myFactory.renew();
			}
			//退出移动保全
			$scope.exit = function(){
				myFactory.exit();
			}

			//确定关闭弹窗
			$scope.certainClose = function(){
				var province = $("#province").find("option:selected").text();
				if (province == "请选择") {
					$.alert({title: '',text: '省/自治区必填！',onOK: function () {}});
					return;
				}
				var city = $("#city").find("option:selected").text();
				if (city == "请选择") {
					$.alert({title: '',text: '市必填',onOK: function () {}});
					return;
				}
				var district = $("#district").find("option:selected").text();
				var districtOptions = $("#district option");
				if (districtOptions.length > 1) {
					if (district == "请选择") {
						$.alert({title: '',text: '区/县必填',onOK: function () {}});
						return;
					}
				} else {
					district = "";
				}

				var town = $("#town").val();
				var country = $("#country").val();
				var address_a = $("#address_a").val();
				if (address_a == "") {
					$.alert({title: '',text: '详细地址必填',onOK: function () {}});
					return;
				}
				$("#address").val(province + city + district + town + country + address_a);
				modal('close','addrModal','addrWindow','addrCloseX');
			}

			//取消关闭弹窗
			$scope.cancelClose = function(){
				modal('close');
			}
			
			//关闭遮罩
			$scope.overwindowClose = function(){
				$(".overwindow").hide();
				$(".overmodal").hide();
			}

			$scope.goBack = function () {
				myFactory.goBack();
			}

			$scope.nextStep = function () {
				//判断是否初始化完成了，如果失败，不予进入下一步
				if(!initFlag){
					myFactory.alert("","初始化时失败，请返回上一步重试","info");
					return false;
				}
				
				/*S2019070309187 - 电子保全增加个人信息授权内容需求 add by yangyan 20190717 start*/
				//检测查阅弹框
		        var readImageFlag = $("#readImageFlag").val();
	    		if(readImageFlag=="false"){
	    			//S2020050812880-个人信息安全项目-修改变更项目录入页面的个人信息授权内容需求 add by yangyan 20200615 start
	    			myFactory.alert('',"请阅读《投保人声明与授权事项》和《中信保诚隐私政策》！",'info');
	    			//S2020050812880-个人信息安全项目-修改变更项目录入页面的个人信息授权内容需求 add by yangyan 20200615 end
	    			return;
	    		}	
	    		/*S2019070309187 - 电子保全增加个人信息授权内容需求 add by yangyan 20190717 end*/
	    		
				//数据校验：
				if ($("#Mobile").val()==""){
					myFactory.alert('','请输入移动电话','info');
					return false;
				}
				if ($("#address").val()=="") {
					$.alert({title: '',text: '请输入通讯地址',onOK: function () {}});
					return false;
				}
				if ($("#address").val().length<6) {
					$.alert({title: '',text: '地址信息不正确，请重新确认',onOK: function () {}});
					return false;
				}
				if($("#ZipCode").val()!=""){
					var zipCode=$("#ZipCode").val();
					//var zipReg=/^[0-9]{6}/;^[1-9]\\d{5}
					var zipReg=/^[0-9]{6}/;
					if(!zipReg.test(zipCode) || zipCode.length>6) {
						$.alert({title: '',text: '邮政编码不正确，请重新确认！',onOK: function () {}});
						return false;
					}
				}else{
					$.alert({title: '',text: '请输入邮政编码',onOK: function () {}});
					return false;
				}
				
				//2014-04-28 客户提出不需要这么严谨的校验
				if($("#Mobile").val()!=""){
					//var mobileReg = /^(13[0-9]|15[012356789]|18[02356789]|14[57])[0-9]{8}$/;
					//更换正则 适配多钟手机，原先的不能适配17开头的手机 BY ZZQ 2017-11-23
					//var mobileReg = /^1[3|4|5|7|8][0-9]{9}$/
					var mobileReg = /^1[0-9]{10}$/;//新需求：1开头，11位数字
					if (!mobileReg.test($("#Mobile").val())) {
						//$("#Mobile").testRemind("手机号码不正确，请重新确认！");
						//myFactory.alert("","手机号码不正确，请重新确认！","info");
						myFactory.alert("","移动电话1不正确，请重新确认！","info");
						return false;
						}
				}
				
				//办公电话改为移动电话2，不需要这些校验
				if($("#CompanyPhone").val()!=""){
					var telReg01=/^\d{3,4}-?\d{7,9}$/;           //020-34688020
					var telReg02=/^\d{7,11}-?\d{4}?$/;           //34688020-3362
					var telReg03=/^\d{3,4}-?\d{7,9}-?\d{4}?$/;   //020-34688020-3362
					var telReg04=/^\d{7,11}$/;                   //34688020
					var telValue=$("#CompanyPhone").val();
					if((!telReg01.test(telValue))&&(!telReg02.test(telValue))&&(!telReg03.test(telValue)&&(!telReg04.test(telValue)))) {
						//$("#CompanyPhone").testRemind("办公电话不正确，请重新确认！");
						//myFactory.alert("","办公电话不正确，请重新确认！","info");
						myFactory.alert("","移动电话2不正确，请重新确认！","info");
						return false;
					}
				}
				
				if($("#HomePhone").val()!=""){
					var telReg01=/^\d{3,4}-?\d{7,9}$/;           //020-34688020
					var telReg02=/^\d{7,11}-?\d{4}?$/;           //34688020-3362
					var telReg03=/^\d{3,4}-?\d{7,9}-?\d{4}?$/;   //020-34688020-3362
					var telReg04=/^\d{7,11}$/;                   //34688020
					var telValue=$("#HomePhone").val();
					if((!telReg01.test(telValue))&&(!telReg02.test(telValue))&&(!telReg03.test(telValue)&&(!telReg04.test(telValue)))) {
						$.alert({title: '',text: '固定电话不正确，请重新确认！',onOK: function () {}});
						return false;
					}
				}
                
				//修改移动电话2校验  BY ZZQ 2017/9/20
				/*if($("#CompanyPhone").val()!=""){
					var mobileReg = /^(13[0-9]|15[012356789]|18[02356789]|14[57])[0-9]{8}$/;
					if (!mobileReg.test($("#CompanyPhone").val())) {
						myFactory.alert("","移动电话2不正确，请重新确认！","info");
						return false;
					}
				}*/
				
				//修改移动电话2校验  BY ZZQ 2017/9/20
				/*if($("#CompanyPhone").val()!=""){
					//var mobileReg = /^(13[0-9]|15[012356789]|18[02356789]|14[57])[0-9]{8}$/;
					//更换正则 适配多钟手机，原先的不能适配17开头的手机 BY ZZQ 2017-11-23
					var mobileReg = /^1[3|4|5|7|8][0-9]{9}$/
					if (!mobileReg.test($("#CompanyPhone").val())) {
						myFactory.alert("","移动电话2不正确，请重新确认！","info");
						return false;
					}
				}*/
				
				//通讯方式后的数据
				item["itemId"] = "01";
				item["mobile"] = $("#Mobile").val();
				item["companyPhone"] = $("#CompanyPhone").val();
				item["homePhone"] = $("#HomePhone").val();
				item["zipCode"] = $("#ZipCode").val();
				item["address"] = $("#address").val();
				item["sourceFlag"] = $("#sourceFlag").val();
				
				//CRS需求，增加个人税收页面  add by dll 2018-01-26 start
				//CRS个人税收居民身份保全需求 增加控制填写投保人、受益人单次填写问题 add by rqyang 2018-12-08 begin
				var proIsChangeFlag=false;
				var proChangeFlagHId=$("#proChangeFlagHId").val();
				var taxName="";
				if(proChangeFlagHId=="1"){//地址栏位省级发生过变化
					var provinceNameOld=$("#provinceNameOld").val();
					var addressNow=$("#address").val();
					var provinceNameNow="";
					for (var i = 0; i < unshow_provinces_b.length; i++) {
						if (addressNow!="" && addressNow!=undefined && addressNow.indexOf(unshow_provinces_b[i]) == 0) {
							provinceNameNow = unshow_provinces_b[i];
							break;
						}
					}
					if (provinceNameNow != "") {//变化后地址是港澳台
						console.log('变更后特别行政区获取省名='+provinceNameNow);
						if(provinceNameOld!=provinceNameNow){
							proIsChangeFlag=true;//地址发生了变化、且变化后的地址仍是港澳台，则需要填写CRS
							taxName=policy.base.surname;
						}
					}
				}
				
				var holderCrsIsexistsFlag=sessionStorage.getItem("HOLDER_CRS_ISEXISTS_FLAG");
				if(proIsChangeFlag && !isOneYearCrtFlag && holderCrsIsexistsFlag=="N"){//一年期保单
					//CRS个人税收居民身份保全需求 增加控制填写投保人、受益人单次填写问题 add by rqyang 2018-12-08 end
					var address = $("#address").val();
					console.log("address:"+address);
					var province="";
					if (address.indexOf("省") > 0) {
						province = address.substr(0, address.indexOf("省") + 1);
						console.log("province:"+province);
					} else if (address.indexOf("特别行政区") > 0) {
						province = address.substr(0, address.indexOf("特别行政区") + 5);
						console.log("province:"+province);
					}
					var type=0;
					for (var i = 0; i < unshow_provinces_b.length; i++) {
						if (province.indexOf(unshow_provinces_b[i]) == 0) {
							type = 2;
							break;
						}
					}
					if(type==2){
						$state.go('tax_info',{
							itemId:item.itemId,
							item:item,
							chdrnum:chdrnum01,
							chdrcoy:chdrcoy,
							isChangeOtherPolicy:$scope.data.radioFlag,
							taxBenefitRole:taxBenefitRole,
							taxClientNo:taxClientNo,
							taxName:taxName
						});
					}else{
						var radioFlag=$scope.data.radioFlag;
						if(radioFlag){//选择是
							item["changeOther"] = "Y";
							$state.go('content_01_list',{
								itemId:'01',item:item,chdrnum01:$scope.chdrnum01,chdrcoy:chdrcoy
							});
						}else{//选择否
							item["changeOther"] = "N";
							$state.go('content_check_main',{
								itemId:item.itemId,
								item:item,
								chdrnum01:chdrnum01,
								chdrcoy:chdrcoy
							});
						}
					}
				}else{
					//原有逻辑分支
					var radioFlag=$scope.data.radioFlag;
					if(radioFlag){//选择是
						item["changeOther"] = "Y";
						$state.go('content_01_list',{
							itemId:'01',item:item,chdrnum01:$scope.chdrnum01,chdrcoy:chdrcoy
						});
					}else{//选择否
						item["changeOther"] = "N";
						$state.go('content_check_main',{
							itemId:item.itemId,
							item:item,
							chdrnum01:chdrnum01,
							chdrcoy:chdrcoy
						});
					}
				}
				//CRS需求，增加个人税收页面  add by dll 2018-01-26 end
			}

			//省市区级联下拉列表
			var regionDataTemp="";
			var citysTemp="";
			var districtsTemp="";
			var unshow_provinces_a = ["北京市", "上海市", "重庆市", "天津市"];
			var unshow_provinces_b = ["台湾省", "香港特别行政区", "澳门特别行政区"];
			var flag = false;
			var proType = 0;//0-普通，1-直辖市，2-特别行政区

			$scope.regionData = [];
			$scope.citys = [];
			$scope.districts = [];
			$scope.regionText = {};
			$scope.$watch('selectedProvince',function(newValue,oldValue){
				//debugger;
				console.log(newValue,oldValue);
				if(newValue != oldValue){
					$("#proChangeFlagHId").val("1");//地址省级行政区发生变化CRS需校验区域变化
					if(!newValue){ //判断选择的是否选择省份，如果没有则重置市区
						$scope.citys = [];
						$scope.districts = [];
						return;
					}
					getAreas("city", newValue);
					$scope.districts = [];
				}
			});

			$scope.$watch('selectedCity',function(newValue,oldValue){
				//debugger;
				if(newValue != oldValue){
					if(!newValue){ //作用同上
						$scope.districts = [];
						return;
					}
					getAreas("district", newValue);
				}
			});
			$scope.districtObj = {};
			$scope.$watch('selectedDstrict',function(newValue,oldValue){
				if(newValue != oldValue){
					var i = 0; len = $scope.districts.length;
					for(i;i < len ; i ++){
						if($scope.districts[i].id == $scope.selectedDstrict){
							$scope.districtObj = $scope.districts[i];
							$scope.regionText.selectedDstrictText = $scope.districts[i].text;
							console.log('区名',$scope.regionText.selectedDstrictText);
						}
					}
				}
			});

			//弹出弹窗
			$scope.chooseAttr = function(){
				var address = $("#address").val();
				modal('open','addrModal','addrWindow','addrCloseX');
				if (!flag) {
					clearAddress();
					initAddr(address);
				}
			}

			function clearAddress() {
				$("#town").val("");
				$("#country").val("");
				$("#address_a").val("");
			}

			function initAddr(address) {
				flag = true;
				var promise = getAreas("province", "0");
				promise.then(function success(returnData) {//成功回调
					var prov = getProvFromAddr(address);//获取省份
					if (prov != null) {
						//获取城市
						var promiseCity = getAreas("city", prov.dutycode);
						promiseCity.then(function success(returnCity) {//成功回调
							address = address.substring(prov.dutyname.length);
							if (prov.type == 0) {
								var city = getCityFromAddr(prov.dutycode, address);//获取城市
								if (city != null) {
									$("#address_a").val(address);
									var promiseDistrict = getAreas("district", city.dutycode);
									promiseDistrict.then(function success(returnDistrict) {//成功回调
										address = address.substring(city.dutyname.length);
										var district = getDistrictFromAddr(city.dutycode, address);
										if (district != null) {
											address = address.substring(district.dutyname.length);
											$("#address_a").val(address);
										}
									},function error(errDistrict) {//错误回调
										console.log(errDistrict);
										alert("获取区异常");
									});
								}
							} else if (prov.type == 1) {
								var cityTemp2=$scope.citys;
								$scope.selectedCity=$scope.citys[0].dutycode;
								var promiseDistrict = getAreas("district", $scope.citys[0].dutycode);
								promiseDistrict.then(function success(returnDistrict) {//成功回调
									var district = getDistrictFromAddr($scope.citys[0].dutycode, address);
									if (district != null) {
										address = address.substring(district.dutyname.length);
										$("#address_a").val(address);
									}
								},function error(errDistrict) {//错误回调
									alert("获取区异常");
								});
							} else if (prov.type == 2) {
								$scope.selectedCity=$scope.citys[0].dutycode;
								var promiseDistrict = getAreas("district", $scope.citys[0].dutycode);
								     promiseDistrict.then(function success(returnDistrict) {//成功回调
								     var districtTemp2=$scope.districts;
									 $scope.selectedDstrict=$scope.districts[0].dutycode;
								 },function error(errDistrict) {//错误回调
								     alert("获取区异常");
								 });
							}
						},function error(errCity) {//错误回调
							console.log(errCity);
							alert("获取城市异常");
						});
					}

					$("#address_a").val(address);
				},function error(err) {//错误回调
					console.log(err);
					alert("获取省份异常");
				});
			}

			function getAreas(objId, pId) {
				var token=sessionStorage.getItem("token");
				var timestamp=myFactory.getTimetamp();
				var sfis= "pId-token-timestamp";
				var signStr="pId="+pId+"&token="+token+"&timestamp="+timestamp;
				var sign = myFactory.hex(signStr);
				var deferred = $q.defer();//声明承诺
				$http({
					method: 'GET',
					url: app.domain + 'common/getAreas.action',
					params: {'pId': pId,'sign':sign,'sfis':sfis,'token':token,'timestamp':timestamp}
				}).then(function successCallback(response) {
					var tmpData = eval(response.data);
					if (tmpData.length > 0) {
						if (objId == "province") {
							$scope.regionData=tmpData;
						}else if(objId == "city"){
							$scope.citys=tmpData;
						}else if(objId == "district"){
							$scope.districts=tmpData;
						}
					}else{
						if(objId == "district"){
							$scope.districts="";
						}
					}
					deferred.resolve(response);//请求成功
				}, function errorCallback(response) {
					alert('查询数据失败!');
				});
				return deferred.promise;//返回承诺
			}

            //获取地址省份
			function getProvFromAddr(address) {
				var province = null;
				var provinceTemp = null;
				var prov = "";
				var type = 0;//0-普通，1-直辖市，2-特别行政区
				for (var i = 0; i < unshow_provinces_a.length; i++) {
					if (address.indexOf(unshow_provinces_a[i]) == 0) {
						prov = unshow_provinces_a[i];
						type = 1;
						break;
					}
				}
				for (var i = 0; i < unshow_provinces_b.length; i++) {
					if (address.indexOf(unshow_provinces_b[i]) == 0) {
						prov = unshow_provinces_b[i];
						type = 2;
						break;
					}
				}
				if (prov == "") {
					if (address.indexOf("省") > 0) {
						prov = address.substr(0, address.indexOf("省") + 1);
					} else if (address.indexOf("自治区") > 0) {
						prov = address.substr(0, address.indexOf("自治区") + 3);
					}
				}
				if (prov != "") {
					provinceTemp=$scope.regionData;
					var i = 0;len = provinceTemp.length;
					for(i;i < len;i ++){
						if(provinceTemp[i].dutyname == prov){
							console.log('省名:'+prov+"provinceTemp[i].dutycode:"+provinceTemp[i].dutycode);
							$scope.selectedProvince=provinceTemp[i].dutycode;
							province = {"dutycode":provinceTemp[i].dutycode, "dutyname":provinceTemp[i].dutyname}
							break;
						}
					}
				}
				if (province != null) {
					province.type = type;
				}
				return province;
			}

            //获取城市
			function getCityFromAddr(pId, address) {
				var city = null;
				var cityTemp=$scope.citys;
				var i = 0;len = cityTemp.length;
				for(i;i < len;i ++){
					if(address.indexOf(cityTemp[i].dutyname) == 0){
						$scope.selectedCity=cityTemp[i].dutycode;
						city = {"dutycode":cityTemp[i].dutycode, "dutyname":cityTemp[i].dutyname}
					}
				}
				return city;
			}

			//获取地区
			function getDistrictFromAddr(pId, address) {
				var district = null;
				var districtTemp=$scope.districts;
				var i = 0;len = districtTemp.length;
				for(i;i < len;i ++){
					if(address.indexOf(districtTemp[i].dutyname) == 0){
						$scope.selectedDstrict=districtTemp[i].dutycode;
						district = {"dutycode":districtTemp[i].dutycode, "dutyname":districtTemp[i].dutyname}
					}
				}
				return district;
			}

			$scope.adCancel = function(){
				modal('close','addrModal','addrWindow','addrCloseX');
				if (!flag) {
					clearAddress();
				}
			}

			//保单详情弹窗
			$scope.showPolicyDetail = function(){
				modal('open','policyModal','policyWindow','policyCloseX');
				var token=sessionStorage.getItem("token");
				var timestamp=myFactory.getTimetamp();
				var sfis= "chdrnum-chdrcoy-token-timestamp";
				var signStr="chdrnum="+chdrnum01+"&chdrcoy="+chdrcoy+"&token="+token+"&timestamp="+timestamp;//encodeURI(name)
				var sign = myFactory.hex(signStr);
				//初始化查询订单详情
				$http({
					method: 'GET',
					url: app.domain + 'query/restFindPolicyDetail.action',
					params: {'chdrnum': chdrnum01,'chdrcoy': chdrcoy,'sign':sign,'sfis':sfis,'token':token,'timestamp':timestamp}
				}).then(function successCallback(response) {
					if (response.data.success) {
						policyData = response.data.data;
						$scope.policyData = policyData;
						$scope.policyData.ptdate01=myFactory.DateTools($scope.policyData.ptdate01);
					}
				}, function errorCallback(response) {
					myFactory.alert("","初始化查询订单详情失败!","info");
				});
			}
			
			//保单详情弹窗关闭函数
			$scope.policyCancel = function(){
				modal('close','policyModal','policyWindow','policyCloseX');
			}

			$scope.exitTest = function () {
				window.location.href = '../index.html';
			}
			
			/*S2019070309187 - 电子保全增加个人信息授权内容需求 add by yangyan 20190717 start*/
			//客户须知弹框
			$scope.tipOpen = function(){
				modal('open','tip_model','policyWindowOn01Input');
			}
			$scope.tipClose = function(){
				modal('close','tip_model','policyWindowOn01Input');
			}
			//页面同意阅读协议复选框部分
			$scope.changeReadFlag = function(){
				$scope.readFlag = !$scope.readFlag;
			}
			/*S2019070309187 - 电子保全增加个人信息授权内容需求 add by yangyan 20190717 end*/
			
			//S2020050812880-个人信息安全项目-修改变更项目录入页面的个人信息授权内容需求 add by yangyan 20200615 start
			$scope.privacyOpen = function(){ 
				$state.go('privacy', {
                    itemId: itemId,
                    chdrnum01: chdrnum01,
                    chdrcoy: chdrcoy
                });
			}
			//S2020050812880-个人信息安全项目-修改变更项目录入页面的个人信息授权内容需求 add by yangyan 20200615 end 
		}])
})(app)